<?php
namespace control;
/*
* 劳务派遣协议类
*/

class laborAgreementClass extends adIndexClass
{
    private const page = 'laborAgreement';
    private const table = 'labor_agreement';
    private const table_detail = 'labor_agreement_detail';
    private const table_company = 'labor_company';
    private const title = '劳务派遣协议';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "orderNo", "title" => "协议编号")) .
            selectMultiple(["name" => "companyId",'title'=>'派遣单位', 'sqlId'=>'id','sqlField'=>'name','table'=>'labor_company','where'=>"state = '启用' order by orderNo",'class' => 'text']) .
            text(array("name" => "startTime", 'class'=>'width200','laydate' => ['type' => 'date', 'range' => '~'], "title" => "开始日期-开始日期")) .
            text(array("name" => "endTime", 'class'=>'width200','laydate' => ['type' => 'date', 'range' => '~'], "title" => "结束日期-结束日期")) .
            select(array("name" => "state", "title" => "审批状态", "option" => $this->stateOption));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'companyId'=>$this->post('companyId'),
            "state" => $this->post('state'),//状态
        );
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'startDate');
        }
        if ($this->post('endTime')) {
            $and .= self::timeComparison($this->post('endTime'), field: 'endDate');
        }

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "signDate desc,time desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, "协议编号", "派遣单位名称", "起止日期", '协议人数', '已派人数', '已退人数', '在派人数', '工作内容', '状态');
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state']=='草稿'?array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"):[],
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $company = query(self::table_company,"id = '$array[companyId]'");
            $totalPeople = static::total(array('table'=>self::table_detail,"where"=>"aid = '$array[id]'"));
            $backPeople = static::total(array('table'=>self::table_detail,"where"=>"aid = '$array[id]' and state = '已退回'"));
            $inPeople = static::total(array('table'=>self::table_detail,"where"=>"aid = '$array[id]' and state = '在派'"));
            $tr[] = array(
                $this->dominate($dominate), $array['orderNo'], $company['name'], $array['startDate'].'至'. $array['endDate'], $array['people'], $totalPeople,
                $backPeople,$inPeople,$array['content'] , $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }




    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
	    $button[]  = [
		    "name"  => L('public.save'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-blue-bg',
	    ];
	    $button[]  = [
		    "name"  => L('public.saveDraft'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-green-bg',
	    ];
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基本信息</span>"
                ],
                [
                    must . "协议编号：" => text(["name" => "orderNo", 'class' => 'text', "value" => $info['orderNo']]),
                    must . "协议名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                ],
                [
                    must . "派遣单位：" => selectMultiple(["name" => "companyId",'title'=>'请选择', 'sqlId'=>'id','sqlField'=>'name','table'=>'labor_company','where'=>"state = '启用' order by orderNo",'class' => 'text', "value" => $info['companyId']]),
                    must . "签订日期：" => text(["name" => "signDate", 'laydate'=>[],'class' => 'text', "value" => $info['signDate']]),
                ],
                [
                    must . "有效开始日期：" => text(["name" => "startDate", 'laydate'=>[],'class' => 'text', "value" => $info['startDate']]),
                    must . "有效结束日期：" => text(["name" => "endDate", 'laydate'=>[],'class' => 'text', "value" => $info['endDate']]),
                ],
                [
                    must . "派遣人数：" => text(["name" => "people", 'type' => 'number', "value" => $info['people']]),
                    "工作内容：" => text(["name" => "content", 'class' => 'width300', "value" => $info['content']]),
                ],
                [
                    "劳务派遣要求：" => textarea(["name" => "requirement", 'class' => 'textarea', "value" => $info['requirement']]),
                    "劳动报酬标准：" => textarea(["name" => "remuneration", 'class' => 'textarea', "value" => $info['remuneration']]),
                ],
                [
                    "<span class='small-title'>附件</span>"
                ],
                [
                     fileUploadClass::addFileComponent($info['id'], '劳务派遣协议', self::page, self::page . 'EditForm'),
                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?:  $this->get('id')]),
            'button' => ' ',
        ]);
        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $field = [
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
            'companyId' => $this->post('companyId'),
            'signDate' => $this->post('signDate'),
            'startDate' => $this->post('startDate'),
            'endDate' => $this->post('endDate'),
            'people' => $this->post('people'),
            'content' => $this->post('content'),
            'requirement' => $this->post('requirement'),
            'remuneration' => $this->post('remuneration'),
        ];
        $annotation = [
            'orderNo' => '协议编号',
            'name' => '协议名称',
            'companyId' =>'派遣单位',
            'signDate' =>'签订日期',
            'startDate' => '有效开始日期',
            'endDate' => '有效结束日期',
            'people' => '派遣人数',
        ];
        $rules = [
            'orderNo' => 'required',
            'name' => 'required',
            'companyId' =>'required',
            'signDate' =>'required|date',
            'startDate' => 'required|date',
            'endDate' => 'required|date',
            'people' => 'required|unsigned_int',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,"where"=>"orderNo = '$field[orderNo]' and id !='$id'")) >0){
            $json['warn'] = '已存在此协议编号';
        }elseif(strtotime($field['endDate']) <=strtotime($field['startDate'])){
            $json['warn'] = '结束日期不能小于开始日期';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '劳务派遣协议',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "menu" => [
                    'detail'=>'基本信息',
                     'peopleList' => ['cla' => 'labor', 'fun' => 'peopleList', 'name' => '派遣清单'],
                ],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿'){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            $company = query(self::table_company,"id = '$info[companyId]'");
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        "协议编号" => $info['orderNo'],
                        "协议名称" => $info['name'],
                        "派遣单位" => $company['name'],
                    ),
                    array(
                        "签订日期" => $info['signDate'],
                        "有效开始日期" => $info['startDate'],
                        "有效结束日期" => $info['endDate'],
                    ),
                    array(
                        "派遣人数" => $info['people'],
                        "工作内容" => $info['content'],
                        '状态'=>$info['state']
                    ),
                    array(
                        "劳务派遣要求" => $info['requirement'],
                    ),
                    array(
                        "劳动报酬标准" => $info['remuneration'],
                    ),
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '劳务派遣协议')
                    )
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }






    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'DetailDelete';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, recordForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
    public function deleteMx()
    {
        $array = $this->post('laborId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table.'_detail', " id = '$id' ");
                $parent = query(self::table, " id = '$info[aid]' ");
                if ($parent['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table.'_detail', "where" => " id = '$id' "));
                    if (static::total(array('table'=>self::table.'_detail','where'=>"laborId = '$info[laborId]'")) ==0){
                        delete(array('table'=>'labor','where'=>"id = '$info[laborId]'"));
                        $all = find(array('table' => "file", "where" => "targetId = '$info[laborId]'"));
                        foreach ($all['array'] as $val) {
                            fileDelete($val['src']);
                        }
                        //删除附件
                        delete(array("table" => 'file', "where" => " targetId = '$info[laborId]' "));
                    }
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了派遣清单，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=".($parent['id']??'');
        }
        return json_encode($json, 320);
    }
}

